import { Component, OnDestroy, AfterViewInit, EventEmitter, Input, Output } from '@angular/core';
import {HttpHeaders} from '@angular/common/http';

@Component({
  selector: 'app-tinymce-editor',
  templateUrl: './tinymce-editor.component.html',
  styleUrls: ['./tinymce-editor.component.css']
})
export class TinymceEditorComponent implements AfterViewInit, OnDestroy {

  constructor() { }

  @Input() elementId: String;
  @Output() onEditorKeyup = new EventEmitter<any>();

  editor;

  uploadFile(url: string, formData: any): void {
    let headers = new HttpHeaders();
    headers.set("Accept", "application/json");
  }

  ngAfterViewInit() {
    let self = this;
    tinymce.init({
      selector: '#my-editor-id',
      plugins: ['link', 'paste', 'table', 'image'],
      skin_url: 'assets/skins/lightgray',
      setup: editor => {
        this.editor = editor;
        editor.on('keyup', () => {
          const content = editor.getContent();
          this.onEditorKeyup.emit(content);
        });
      },
    images_upload_handler: function(blobInfo, success, failure) {
        var formData;
        formData = new FormData;
        formData.append("file", blobInfo.blob(), blobInfo.filename());
        self.uploadFile("/api/upload", formData);
        // this.uploadFile("/api/upload", formData).subscribe(data => {
        // console.log(data);
        // success(data["serverPath"]);
    // });
     }
    });
  }

  ngOnDestroy() {
    tinymce.remove(this.editor);
  }


}
